import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyJWT } from '@/lib/jwt'

export async function middleware(request: NextRequest) {
  console.log('🚀 Middleware triggered for path:', request.nextUrl.pathname)
  
  const token = request.cookies.get('vertu-auth-token')?.value
  const path = request.nextUrl.pathname
  
  console.log('🔐 Token exists:', !!token)
  console.log('📍 Current path:', path)

  // 定义不需要鉴权的公共路径
  const publicPaths = [
    '/login',
    '/signup',
    '/chat',
    '/api/auth/login',
    '/api/auth/logout',
    '/api/auth/signup',
    '/auth/callback',
  ]
  
  const isPublicPath = publicPaths.some(p => path.startsWith(p))
  console.log('🌐 isPublicPath:', isPublicPath)

  // 验证 JWT token
  let isAuthenticated = false
  if (token) {
    const payload = await verifyJWT(token)
    isAuthenticated = !!payload
    console.log('🔓 JWT valid:', isAuthenticated)
    if (payload) {
      console.log('👤 User:', payload.username)
    }
  }

  // 如果用户未认证，并且访问的不是公共路径，则重定向到登录页面
  if (!isAuthenticated && !isPublicPath) {
    console.log('🔄 Redirecting to /login due to unauthenticated access from:', path)
    const redirectUrl = new URL('/login', request.url)
    redirectUrl.searchParams.set('redirectedFrom', path)
    return NextResponse.redirect(redirectUrl)
  }

  // 如果用户已认证，并且访问的是登录页面，则重定向到仪表盘
  if (isAuthenticated && path === '/login') {
    console.log('🔄 Redirecting to /dashboard due to authenticated access to login page.')
    return NextResponse.redirect(new URL('/dashboard', request.url))
  }

  console.log('✅ Middleware completed, allowing access to:', path)
  return NextResponse.next()
}

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|jpeg|gif|webp|svg|css|js)$).*)',
  ],
}